import React, { useEffect, useRef, useState } from 'react'
interface MyLazyLoadProps {
    className?: string
    style?: React.CSSProperties
    placeholder?: React.ReactNode
    children: React.ReactNode
    offset?: number
    width?: number
    height?: number
    onContentVisible?: () => void
}
export default function MyLazyLoad(props: MyLazyLoadProps) {
    const { className="", style, placeholder, children, offset=0, width, height, onContentVisible } = props
    const [visible, setVisible] = useState(false)
    const elementObserver=useRef<IntersectionObserver>()
    const containerRef=useRef<HTMLDivElement>(null)
    function lazyLoadHandler(entries:IntersectionObserverEntry[]){
        const entry=entries[0]
        if(entry.isIntersecting){
            setVisible(true)
            onContentVisible?.()
            const node=containerRef.current
            if(node){
                elementObserver.current?.unobserve(node)//解绑观察关系
            }
        }
    }
    const options={
        rootMargin:`${offset}px`,//距离可视窗口的距离
        threshold:0,//交叉比例
    }
    useEffect(()=>{
        elementObserver.current=new IntersectionObserver(lazyLoadHandler,options)
        const node=containerRef.current
        if(node){
            elementObserver.current?.observe(node)//绑定观察关系
        }
    },[])
    return (
        <div className={className} style={style} ref={containerRef}>
            {visible ? children : placeholder}
        </div>
    )
}
